# # 
#  expectit.py
#  ExpectIT
#  
#  Author: Marvin S. Addison
#  Date: 2007-10-15
#  Version: $Revision: $
#  Updated: $Date: $
#  Copyright 2008 Marvin S. Addison. All rights reserved.
#  See LICENSE.txt for licensing information.
# 

#!/usr/bin/env python

import pexpect
import sys
import yaml
from expectit import crypt
from expectit import Auth
from expectit import Session
from expectit.util import printerr, read_file, quit

yml = ''
config = 'config.yml'
if len(sys.argv) > 1:
	if sys.argv[1] == 'crypt':
		# User wants crypto functions
		# Make sure we have at least 3 args
		if len(sys.argv) < 4:
			crypt.usage()
			sys.exit()
		crypt.main(sys.argv[2:])
		sys.exit()
	else:
		# Normal mode
		config = sys.argv[1]
		printerr('Using configuration file at %s' % config)

cfg = None
try:
	f = None	
	try:
		cfg = yaml.load(read_file(config))
	except IOError, ioe:
		printerr('Cannot read expect-it config file at %s' % config)
	except yaml.YAMLError, ye:
		printerr('Cannot parse expect-it config file at %s' % config)
		printerr('Probably a YAML syntax error. Error details:\n%s' % ye)
		quit('Cannot continue without configuration.')
finally:
	if f: f.close() 
	
for host in cfg['hosts']:
	sess = Session.from_dict(host)
	if not sess.auth:
		printerr('No per-host auth credentials for %s.' % host['host'])
		printerr('Falling back to credentials in master_auth.')
		sess.auth = Auth.from_dict(cfg['master_auth'])
	if sess.auth.method == 'password':
		sess.auth.credential = crypt.decrypt(cfg['crypt_key'], \
			sess.auth.credential)
	try:
		try:
			sess.connect()
			sess.execute()
		except Exception, e:
			printerr('Session error on host %s:\n%s' % (host['host'], e))
	finally:
		if sess.is_connected: sess.disconnect()
